package com.df.tv.launcher.activity;

import android.app.WallpaperInfo;
import android.app.WallpaperManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Point;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.WindowManager;

import com.df.tv.launcher.R;
import com.df.tv.launcher.fragment.LoadingFragment;
import com.df.tv.launcher.fragment.MainFrameFragment;
import com.df.tv.launcher.params.ComParams;
import com.telecom.tv189.comlib.models.ClickLogSender;
import com.telecom.tv189.comlib.switcher.MethodSwitcher;
import com.telecom.tv189.comlib.switcher.annotation.SwitchMethod;
import com.telecom.tv189.comlib.switcher.annotation.SwtichCase;
import com.telecom.tv189.comlib.util.Log;
import com.telecom.tv189.silentlogin.OnInfoChangedListener;
import com.telecom.tv189.silentlogin.UserInfo;
import com.telecom.tv189.silentlogin.UserInfoKeeper;

/**
 * Launcher的Activity,Launcher的UI内容全部由fragment来显示
 * 
 * @author xiao
 * 
 */
public class MainActivity extends FragmentActivity {

    public interface OnHomePressedListener {
        public boolean onHomePressed();
    }

    private static final String TAG = "MainActivity";

    private static final String METHOD_REFRESH_UI_UNBIND = "refreshUIUnbind";

    private static final String ACTION_INIT = "com.telecom.tv189.tm.action.INIT";

    private boolean mUIStarted;
    private boolean mFirstRefresh;
    private String mPhone;
    private String mToken;
    private MyOnInfoChangedListener mInfoListener;
    private onAppRefreshListener mOnRefreshListener;

    private Fragment mMainUI;

    private WallpaperSwitcher mSwitcher;

    private MyServiceConnection mConnection = new MyServiceConnection();
    private boolean mBoundTm;

    private OnHomePressedListener mHomePressedListener;

    private boolean mHasWindowFocus;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate()");
        super.onCreate(savedInstanceState);
        getWindow().setFormat(PixelFormat.RGBA_8888);
        setContentView(R.layout.main_activity);

        mSwitcher = new WallpaperSwitcher();

        mUIStarted = false;
        mFirstRefresh = true;
        mInfoListener = new MyOnInfoChangedListener();

        ClickLogSender.getInstance(this).init();
        ClickLogSender.getInstance(this).flushDelayed(5 * 60 * 1000);

        startControlServer();

        mBoundTm = false;
        tryBindTerminalMgr();

        mHasWindowFocus = false;
    }

    @Override
    protected void onRestart() {
        Log.d(TAG, "onRestart()");
        super.onRestart();
    }

    @Override
    protected void onStart() {
        Log.d(TAG, "onStart()");
        super.onStart();
    }

    @Override
    protected void onResume() {
        Log.d(TAG, "onResume()");
        super.onResume();
        mSwitcher.register();
        refreshUI();
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause()");
        super.onPause();
        mSwitcher.unregister();
        UserInfoKeeper.getInstance().removeListener(mInfoListener);
    }

    @Override
    protected void onStop() {
        Log.d(TAG, "onStop()");
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "onDestroy()");
        super.onDestroy();
        mInfoListener = null;
        ClickLogSender.getInstance(this).destory();
        if (mBoundTm)
            unbindService(mConnection);
        mBoundTm = false;
    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        super.onActivityResult(arg0, arg1, arg2);

        if (mOnRefreshListener != null) {
            mOnRefreshListener.onRefresh(arg0, arg1, arg2);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        Log.d(TAG, "onWindowFocusChanged(" + hasFocus + ")");
        super.onWindowFocusChanged(hasFocus);
        mHasWindowFocus = hasFocus;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (mHasWindowFocus && mHomePressedListener != null)
            mHomePressedListener.onHomePressed();
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN) {
            switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                return true;
            case KeyEvent.KEYCODE_HOME:
                return true;
            }
        }
        else if (event.getAction() == KeyEvent.ACTION_UP) {
            switch (event.getKeyCode()) {
            case KeyEvent.KEYCODE_BACK:
                if (!event.isCanceled()) {
                    // Do BACK behavior.
                }
                return true;
            case KeyEvent.KEYCODE_HOME:
                if (!event.isCanceled()) {
                    // Do HOME behavior.
                }
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    private void tryBindTerminalMgr() {
        if (!mBoundTm) {
            Intent service = new Intent("com.telecom.tv189.service.KeepTouchService");
            mBoundTm = bindService(service, mConnection, BIND_AUTO_CREATE);
        }
    }

    private void refreshUI() {
        tryBindTerminalMgr();
        UserInfo info = UserInfoKeeper.getInstance().getInfo();
        if (!mBoundTm || info == null) {
            // tm 未安装
            startUI(true);
            Log.i(TAG, "can not connect to tm，just start ui");
        }
        else {
            Log.d(TAG, "state=" + info.getState());
            Log.d(TAG, "phone=" + info.getPhone());
            if (mFirstRefresh) {
                // 初次刷新界面
                stopUI(true);
                Log.i(TAG, "first time for refresh ui, stop ui and start init");
                mFirstRefresh = false;
            }
            else {
                // 非初次刷新界面
                Log.i(TAG, "later time for refresh ui");
                if ("LOGIN".equals(info.getState())) {
                    // 已登录
                    if (TextUtils.isEmpty(info.getPhone())) {
                        // 未绑定用户
                        refreshUIUnbind(info);
                    }
                    else {
                        // 已绑定用户
                        String phone = info.getPhone();
                        if (TextUtils.isEmpty(phone) || !phone.equals(mPhone) || TextUtils.isEmpty(mToken)) {
                            // 用户更新
                            startUI(true);
                            Log.i(TAG, "user changed, start ui force");
                        }
                        else {
                            // 用户一致
                            startUI(false);
                            Log.i(TAG, "user accordance, start ui");
                        }
                    }
                }
                else {
                    // 未登录
                    startUI(false);
                    Log.i(TAG, "unlogin, start ui");
                }
                mPhone = info.getPhone();
                mToken = info.getToken();
            }
        }
    }

    private void refreshUIUnbind(UserInfo info) {
        MethodSwitcher.invoke(this, METHOD_REFRESH_UI_UNBIND, info);
    }

    @SwitchMethod(METHOD_REFRESH_UI_UNBIND)
    @SwtichCase(ComParams.CASE_V4)
    public void refreshUIUnbindV400(UserInfo info) {
        stopUI(false);
        Log.i(TAG, "unbind, case v400, stop ui");
    }

    @SwitchMethod(METHOD_REFRESH_UI_UNBIND)
    @SwtichCase(ComParams.CASE_V5)
    public void refreshUIUnbindV520(UserInfo info) {
        if (TextUtils.isEmpty(mPhone)) {
            // 状态未变化
            startUI(false);
            Log.i(TAG, "unbind, case v520, start ui");
        }
        else {
            // 绑定－>未绑定
            startUI(true);
            Log.i(TAG, "bind to unbind, case v520, start ui force");
        }
    }

    private void startControlServer() {
        try {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName("com.telecom.ott.control.server",
                    "com.telecom.ott.control.server.server.OTTControlService"));
            startService(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void startUI(boolean force) {
        UserInfoKeeper.getInstance().addListener(mInfoListener);
        if (!mUIStarted || force) {
            mMainUI = new MainFrameFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_container, mMainUI).commit();
            mUIStarted = true;
        }
    }

    private void stopUI(boolean force) {
        if (mUIStarted || force) {
            mMainUI = new LoadingFragment();
            getSupportFragmentManager().beginTransaction().replace(R.id.main_frame_container, mMainUI).commit();
            mUIStarted = false;
        }
        UserInfoKeeper.getInstance().removeListener(mInfoListener);
        //启动初始化流程以显示配对界面
        startInit();
    }

    private void startInit() {
        Intent i = new Intent(ACTION_INIT);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        startActivity(i);
    }

    public void setOnHomePressedListener(OnHomePressedListener listener) {
        mHomePressedListener = listener;
    }

    /**
     * 直接使用系统wallpaper会导致视频问题。所以在launcher内部设置背景图片。<br/>
     * 已知视频问题如下：<br/>
     * 1.视频大小和view大小不一致（偏大）<br/>
     * 2.视频区域无法被其他view覆盖后，仍然可以看见 <br/>
     * 3.有时会出现无视频的现象
     */
    private class WallpaperSwitcher extends BroadcastReceiver {

        private static final boolean SUPPORT_LIVE_WALLPAPER = false;

        private WallpaperManager mWallpaperManager;
        private WallpaperInfo mWallpaperInfo;

        public WallpaperSwitcher() {
            mWallpaperManager = WallpaperManager.getInstance(getApplicationContext());
        }

        @SuppressWarnings("deprecation")
        public void register() {
            registerReceiver(this, new IntentFilter(Intent.ACTION_WALLPAPER_CHANGED));
            setWallpaper();
        }

        public void unregister() {
            unregisterReceiver(this);
        }

        public void setWallpaper() {
            WallpaperInfo wpi = mWallpaperManager.getWallpaperInfo();
            //只支持静态壁纸
            if (SUPPORT_LIVE_WALLPAPER && wpi != null)
                setLiveWallpaper(wpi);
            else
                setStaticWallpaper();
        }

        private void checkSize() {
            // ensure the size of wallpaper is same as the screen
            Point p = new Point();
            getWindowManager().getDefaultDisplay().getSize(p);
            int width = mWallpaperManager.getDesiredMinimumWidth();
            int height = mWallpaperManager.getDesiredMinimumHeight();
            if (width != p.x || height != p.y)
                mWallpaperManager.suggestDesiredDimensions(p.x, p.y);
        }

        private void setLiveWallpaper(WallpaperInfo wpi) {
            if ((mWallpaperInfo != null) && (wpi.getComponent().equals(mWallpaperInfo.getComponent())))
                return;
            mWallpaperInfo = wpi;
            checkSize();
            getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER,
                    WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
        }

        private void setStaticWallpaper() {
            mWallpaperInfo = null;
            checkSize();
            getWindow().setBackgroundDrawable(mWallpaperManager.getFastDrawable());
            getWindow().setFlags(~WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER,
                    WindowManager.LayoutParams.FLAG_SHOW_WALLPAPER);
        }

        @Override
        public void onReceive(Context context, Intent intent) {
            setWallpaper();
        }
    }

    private class MyOnInfoChangedListener implements OnInfoChangedListener<UserInfo> {

        @Override
        public void onChanged(UserInfo arg0) {
            refreshUI();
        }
    }

    /**
     * Add suspend lisetner.
     * 
     * @param l
     */
    public void setOnRefreshListener(onAppRefreshListener l) {
        this.mOnRefreshListener = l;
    }

    /**
     * Interface for callback.
     * 
     * @author pc1
     * 
     */
    public interface onAppRefreshListener {
        void onRefresh(int requestCode, int resCode, Intent data);
    }

    /**
     * 与tm失连，重启
     * 
     * @author xiao
     * 
     */
    private class MyServiceConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "keep touch with TerminalMgr");
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e(TAG, "lost touch with TerminalMgr! exit(-1)");
            System.exit(-1);
        }
    }
}
